package com.eystar.pdc.controller;

import java.util.List;

import com.eystar.ext.route.ControllerBind;
import com.eystar.pdc.aop.auth.AuthAnno;
import com.eystar.pdc.aop.auth.AuthAnno.AuthType;
import com.eystar.pdc.aop.log.LogAnno;
import com.eystar.pdc.aop.log.LogAnno.LogType;
import com.eystar.pdc.model.AuthSign;
import com.eystar.pdc.model.Resource;
import com.eystar.pdc.model.ResourceTree;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 资源管理 
 * @author auth
 *
 */
@ControllerBind(controllerKey="/resource",viewPath="/pdc")
@AuthAnno(type = AuthType.Super, res = "resource")
public class ResourceController extends BaseController {

	/**
	 * 跳转到首页
	 */
	@AuthAnno(auth = "look")
	@LogAnno(desc = "查看资源列表", type = LogType.SAVE)
	public void index() throws Exception{
		List<AuthSign> authSigns = AuthSign.dao.findAll();
		setAttr("signs", authSigns);
		render("resource_list.html");
	}
	
	/**
	 * 树形结构展示
	 * @throws Exception
	 */
	public void tree() throws Exception{
		String json = ResourceTree.dao.listResourceTreeJson(false);
		renderJson(json);
	}
	
	/**
	 * 点击保存按钮
	 * @throws Exception
	 */
	@AuthAnno(auth = "save")
	@LogAnno(desc = "添加资源${resource.res_name}", type = LogType.SAVE)
	public void save() throws Exception{
		Resource resource = null;
		try {
			resource = getSaveModel(Resource.class);
			if(StrUtil.isBlank(resource.getStr("menu_remark"))){
				resource.set("menu_remark", resource.getStr("res_remark"));
			}
			if(StrUtil.isBlank(resource.getStr("res_icon"))){
				resource.set("res_icon", "fa fa-tasks");
			}
			resource.set("auth_signs", ArrayUtil.join(getParaValues("resource.auth_signs"),","));
			resource.save();
			Resource.dao.addResourcePath(resource);
			Resource.dao.refresh(true);
			renderJson(ok());
		} catch (Exception e) {
			logger.error("保存出错！" + resource.toJson(), e);
			renderJson(fail());
		}
	}
	
	/**
	 * 点击修改按钮
	 * @throws Exception
	 */
	@AuthAnno(auth = "update")
	@LogAnno(desc = "修改资源${resource.res_name}", type = LogType.UPDATE)
	public void update() throws Exception{
		Resource resource = null;
		try {
			resource = getUpdateModel(Resource.class);
			if(StrUtil.isBlank(resource.getStr("menu_remark"))){
				resource.set("menu_remark", resource.getStr("res_remark"));
			}
			resource.set("auth_signs", ArrayUtil.join(getParaValues("resource.auth_signs"),","));
			resource.update();
			Resource.dao.updateResourcePath(resource);
			Resource.dao.refresh(true);
			renderJson(ok());
		} catch (Exception e) {
			logger.error("修改出错！" + resource.toJson(), e);
			renderJson(fail());
		}
	}
	
	/**
	 * 删除方法
	 */
	@AuthAnno(auth = "delete")
	@LogAnno(desc = "删除资源", type = LogType.DELETE)
	public void delete() throws Exception{
		Resource.dao.deleteResourceById(getPara());
		Resource.dao.refresh(true);
		redirect("/resource");
	}
}